<?php
namespace admin\controllers;


use admin\models\UserComment;
use Yii;
use yii\data\Pagination;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

/**
 * Created by PhpStorm.
 * User: 沈小鱼
 * Date: 2016/7/26
 * Time: 19:37
 */
class CommentController extends BaseController{



    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['add','list','del'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                ],
            ],
        ];
    }



    public function actionList(){
        $user_id = Yii::$app->request->get('user_id');
        $data = UserComment::find()->where('mu_id='.$user_id);
        $commentPages = new Pagination([
            'totalCount' =>$data->count(),
            'pageSize' => '5',
            'pageSizeParam' => false,
        ]);
        $comments = $data->offset($commentPages->offset)->limit($commentPages->limit)->all();
        return $this->renderPartial('list',[
            'commentPages'=>$commentPages,
            'comments'=>$comments,
        ]);
    }


    public function actionAdd(){
        $admin = Yii::$app->user->identity->getId();
        if(empty($admin)){
            return $this->showResult(302,'用户已登出');
        }
        $user_id = Yii::$app->request->get('id');
        if(empty($user_id)){
            return $this->showResult(301,'读取用户信息失败');
        }
        $commentArr = Yii::$app->request->post('UserComment');
        $comment = new UserComment();
        $comment->attributes = $commentArr;
        $comment->mu_id = $user_id;
        $comment->ma_id = $admin;
        if(!$comment->save()){
            return $this->showResult(400,'保存失败');
        }else{
            return $this->showResult(200,'保存成功');
        }
    }

    public function actionDel(){
        $mc_id = Yii::$app->request->post('mc_id');
        if(empty($mc_id)){
            return $this->showResult(301,'未获取到印象信息');
        }
        $admin = Yii::$app->user->identity;
        if(empty($admin)){
            return $this->showResult(302,'您的登录信息已失效，请重新登录');
        }
        $comment = UserComment::findOne($mc_id);
        if(empty($comment)){
            return $this->showResult(301,'该条记录已不存在');
        }
        $row = Yii::$app->db->createCommand('delete from mm_user_comment WHERE mc_id='.$mc_id)->execute();
        if(!empty($row)){
            return $this->showResult(200,'删除成功');
        }else{
            return $this->showResult(400,'删除失败');
        }
    }

}